package game.module.payment.processor;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.ObjectMapper;

import game.HallServer;
import game.common.AwardConstants;
import game.common.PlayingRoleMsgProcessor;
import game.entity.PlayingRole;
import game.module.award.logic.AwardUtil;
import game.module.award.logic.ModuleConstants;
import game.module.item.dao.ShopTemplateCache;
import game.module.payment.dao.PaymentLogDao;
import game.module.payment.logic.PaymentManager;
import game.module.template.ShopTemplate;
import game.module.user.bean.PlayerBean;
import game.module.user.dao.PlayerDao;
import game.session.PlayerOnlineCacheMng;
import game.session.SessionManager;
import lion.common.MsgCodeAnn;
import lion.netty4.message.MyRequestMessage;
import lion.netty4.message.RequestMessageRaw;
import lion.netty4.message.RequestProtoMessage;
import lua.LuaMessageHall.C2SIosVerify;
import lua.LuaMessageHall.PushIosVerify;
import lua.LuaMessageHall.S2CIosVerify;
import sdk.iap.IOSVerify;

@MsgCodeAnn(msgcode = C2SIosVerify.id, accessLimit = 500)
public class IosVerifyProcessor extends PlayingRoleMsgProcessor {

	private static Logger logger = LoggerFactory.getLogger(IosVerifyProcessor.class);

	@SuppressWarnings("unchecked")
	@Override
	public void process(PlayingRole playingRole, RequestMessageRaw requestMessage) throws Exception {
		C2SIosVerify iosVerifyMsg = C2SIosVerify.parse(requestMessage);
		String locale = iosVerifyMsg.locale;
		final String receipt = iosVerifyMsg.receipt;
		final String openId = playingRole.getPlayerBean().getAccountId();
		final int playerId = playingRole.getId();
		final int serverId = 0;
		logger.info("ios verify,locale={},receipt={}", locale, receipt);
		String ipAddrRaw = playingRole.getGamePlayer().getAddress();
		final String ipAddr = getIpAddr(ipAddrRaw);
		// String md5_receipt = IOSVerify.md5(receipt);
		S2CIosVerify respMsg = new S2CIosVerify();
		playingRole.writeAndFlush(respMsg.build(playingRole.alloc()));
		HallServer.executorService.execute(new Runnable() {
			public void run() {
				try {
					String verifyResult = IOSVerify.buyAppVerify(receipt,
							HallServer.getInstance().getServerConfig().isIosIapIsSandbox());
					logger.info("verifyResult={}", verifyResult);
					// {"receipt":{"original_purchase_date_pst":"2016-03-30
					// 18:59:03
					// America/Los_Angeles", "purchase_date_ms":"1459389543146",
					// "unique_identifier":"927e4e26aeb27d3bee73e32a5923838b432ea784",
					// "original_transaction_id":"1000000202536175",
					// "bvrs":"1.0",
					// "transaction_id":"1000000202536175", "quantity":"1",
					// "unique_vendor_identifier":"8104B566-30F0-4DC1-8B45-DCA0703B4447",
					// "item_id":"1098078290",
					// "product_id":"cn.xxcaifu.diamond001",
					// "purchase_date":"2016-03-31 01:59:03 Etc/GMT",
					// "original_purchase_date":"2016-03-31 01:59:03 Etc/GMT",
					// "purchase_date_pst":"2016-03-30 18:59:03
					// America/Los_Angeles", "bid":"com.xxcaifu.game",
					// "original_purchase_date_ms":"1459389543146"}, "status":0}
					if (verifyResult == null) {
						// 苹果服务器没有返回验证结果
						PushIosVerify pushMsg = new PushIosVerify(1, 0, "");
						playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
					} else {
						// 跟苹果验证有返回结果------------------
						ObjectMapper mapper = new ObjectMapper();
						Map<String, Object> job;
						job = mapper.readValue(verifyResult, Map.class);
						Integer status = (Integer) job.get("status");
						if (status == 0)// 验证成功
						{
							Map<String, Object> returnJson = (Map<String, Object>) job.get("receipt");
							// 产品ID TODO 判断是否是我们产品
							String product_id = (String) returnJson.get("product_id");
							// 数量
							String quantity = (String) returnJson.get("quantity");
							// TODO 判断Transaction Identifier是否已经存在
							String transaction_id = (String) returnJson.get("transaction_id");
							// 交易日期
							String purchase_date = (String) returnJson.get("purchase_date");
							// 订单是否存在
							boolean orderExist = PaymentLogDao.getInstance().checkOrderExist(transaction_id);
							if (orderExist) {
								logger.info("ios payment,order exist1,playerId={},orderid={}", playingRole.getId(),
										transaction_id);
								PushIosVerify pushMsg = new PushIosVerify(2, 0, "");
								playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
								return;
							}
							// 商品是否存在
							if (!product_id.startsWith("com.guanqu")) {
								PushIosVerify pushMsg = new PushIosVerify(3, 0, "");
								playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
								return;
							}
							//
							product_id = product_id.substring(product_id.lastIndexOf(".") + 1);
							ShopTemplate iosRechargeTemplate = ShopTemplateCache.getInstance()
									.getIosRechargeTemplateById(product_id);
							if (iosRechargeTemplate == null) {
								PushIosVerify pushMsg = new PushIosVerify(2, 0, "");
								playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
								return;
							}
							if (PaymentManager.getInstance().checkOrderExist(transaction_id)) {
								logger.info("ios payment,order exist2,playerId={},orderid={}", playingRole.getId(),
										transaction_id);
								PushIosVerify pushMsg = new PushIosVerify(2, 0, "");
								playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
								return;
							}
							// 保存log
							PlayerBean pb = PlayerOnlineCacheMng.getInstance().getCache(openId, 0);
							// PaymentManager.getInstance().addPayPlayer(pb != null ? pb.getId() : 0);
							PaymentManager.getInstance().addOrderId(transaction_id);
							// 玩家是否在线
							PlayingRole pr = SessionManager.getInstance().getPlayer(playerId);
							// 是否进行首冲
							int addDiamond = iosRechargeTemplate.getNum();
//							boolean isFirstRecharge = false;
//							if (pr != null) {
//								PlayerExtraBean playerExtraBean = PlayerExtraCache.getInstance()
//										.getPlayerExtraBean(playerId);
//								if (playerExtraBean == null || playerExtraBean.getIsRecharge() == null
//										|| playerExtraBean.getIsRecharge() == 0) {
//									isFirstRecharge = true;
//								}
//							} else {
//								isFirstRecharge = PlayerExtraDao.getInstance().isFirstRecharge(playerId);
//							}
							// 是否为青春基金
							boolean isQingChunJiJIn = false;
							// 进行支付
							int sumDiamond = addDiamond;
							// 首冲奖励钻石
							if (!PaymentLogDao.getInstance().checkRechargeExist(iosRechargeTemplate.getId(), openId,
									serverId)) {
								sumDiamond = addDiamond * 2;
							}
							// 更新数据库
							logger.info("update db,addDiamond={},openId={}", sumDiamond, openId);
							PlayerDao.getInstance().addMoney(sumDiamond, openId);
							// 更新玩家钻石
							if (pr != null) {
								AwardUtil.send(pr, AwardConstants.FANG_KA, sumDiamond, ModuleConstants.MODULE_PAY);
								PushIosVerify pushMsg = new PushIosVerify(0, sumDiamond, transaction_id);
								pr.getGamePlayer().writeAndFlush(pushMsg.build(pr.alloc()));
							} else {
								if (pb != null) {
									pb.setFang_ka(pb.getFang_ka() + sumDiamond);
								}
							}
							// 保存log
							PaymentLogDao.getInstance().saveTopupLog(pb != null ? pb.getId() : 0,
									iosRechargeTemplate.getId(), transaction_id, iosRechargeTemplate.getNum() * 10,
									openId);
						} else {
							// 账单无效
							PushIosVerify pushMsg = new PushIosVerify(4, 0, "");
							playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
						}
					}
				} catch (Exception e) {
					logger.error("", e);
					PushIosVerify pushMsg = new PushIosVerify(4, 0, "");
					playingRole.getGamePlayer().writeAndFlush(pushMsg.build(playingRole.alloc()));
				}
			}
		});
	}

	@Override
	public void processProto(final PlayingRole playingRole, RequestProtoMessage request) throws Exception {

	}

	public static String getIpAddr(String ipAddrRaw) {
		String retStr = ipAddrRaw;
		int fenIndex = ipAddrRaw.indexOf(":");
		if (fenIndex >= 0) {
			retStr = retStr.substring(0, fenIndex);
		}
		if (retStr.startsWith("/")) {
			retStr = retStr.substring(1);
		}
		return retStr;
	}

	public static void main(String[] args) {
		String vipProduceStr = "cn.xxcaifu.chengzhang1001";
		String ret = vipProduceStr.substring(vipProduceStr.lastIndexOf(".") + 1);
		System.out.println(ret);
	}

	@Override
	public void processWebsocket(PlayingRole playingRole, MyRequestMessage request) throws Exception {
		// TODO Auto-generated method stub

	}

}
